
def crc16(x, invert):
    init = 0xFFFF
    poly = 0xA001

    for byte in x:
        init ^= byte
        for i in range(8):
            last = init % 2
            init >>= 1
            if last == 1:
                init ^= poly
    hex_s = hex(init).upper()
    return hex_s[4:6] + hex_s[2:4] if invert else hex_s[2:4] + hex_s[4:6]


def crc16Bytes(x, invert):
    crc_hex = crc16(x, invert)
    crc_int = int(crc_hex, 16)
    byte_len = int(crc_int.bit_length() / 8 + 1)
    if (byte_len < 2):
        byte_len = 2

    bytes_list = []
    bytes_list = crc_int.to_bytes(length=byte_len,
                                  byteorder='big',
                                  signed=True)
    if (byte_len >= 3):
        bytes_list = bytes_list[1:]

    readcrcout = bytes(bytes_list)
    return readcrcout
